import numpy as np
import matplotlib.pyplot as plt


raw_data_X= [[3.399,2.33],
            [3.11,1.799],
            [1.399,3.31],
            [3.59,4.91],
            [2.21,2.69],
            [7.193,6.30],
            [5.31,5.91],
            [9.29,5.19],
            [9.99,6.19],]

raw_data_y=[0,0,0,0,0,1,1,1,1]
# print(raw_data_X)
# print(raw_data_y)

X_train=np.array(raw_data_X)
y_train=np.array(raw_data_y)
print(X_train)
print(y_train)
X_predict=[1.31,3.9]
x_predict=np.array(X_predict)

#X_train[y_train==0,0]：y_train==0选定标签为0的样本，第二个0表示矩阵的第一列
plt.scatter(X_train[y_train==0,0],X_train[y_train==0,1],color='r')

plt.scatter(X_train[y_train==1,0],X_train[y_train==1,1],color='g')
plt.scatter(x_predict[0],x_predict[1],color='b')

plt.show()#图像绘制


#分别与每一个样本进行计算，求距离，存到distance列表
from math import sqrt
distance=[]
for x_train in X_train:
    d1=sqrt(sum(x_train-x_predict)**2)
    distance.append(d1)

print(distance)
#从小到大排序，获取是下标
arg_sort=np.argsort(distance)
print(arg_sort)



k=3
top_y=[y_train[i] for i in arg_sort[:k]]
print(top_y)

from collections import Counter
#计数函数会统计标签对应的个数，类型为字典
predict_votes=Counter(top_y)
print(predict_votes)

result=predict_votes.most_common(1)
print(result)

y_predict=result[0][0]
print(y_predict)